/**
 * 视频播放优化工具类
 * 专门针对低带宽环境下的视频播放优化
 */

export interface NetworkInfo {
  type: string;
  effectiveType: string;
  downlink?: number;
  rtt?: number;
  saveData?: boolean;
}

export interface VideoOptimizationConfig {
  preloadMode: 'none' | 'metadata' | 'auto';
  maxRetries: number;
  timeoutDuration: number;
  bufferThreshold: number;
  preloadCount: number;
  enableAdaptiveQuality: boolean;
}

export class VideoOptimizer {
  private static instance: VideoOptimizer;
  private networkInfo: NetworkInfo = { type: 'unknown', effectiveType: 'unknown' };
  private isSlowNetwork = false;
  private config: VideoOptimizationConfig;

  private constructor() {
    this.config = this.getDefaultConfig();
    this.detectNetwork();
  }

  public static getInstance(): VideoOptimizer {
    if (!VideoOptimizer.instance) {
      VideoOptimizer.instance = new VideoOptimizer();
    }
    return VideoOptimizer.instance;
  }

  /**
   * 获取默认配置
   */
  private getDefaultConfig(): VideoOptimizationConfig {
    return {
      preloadMode: 'metadata',
      maxRetries: 3,
      timeoutDuration: 30000,
      bufferThreshold: 30,
      preloadCount: 1,
      enableAdaptiveQuality: true
    };
  }

  /**
   * 检测网络状况
   */
  public detectNetwork(): NetworkInfo {
    if ('connection' in navigator) {
      const connection = (navigator as any).connection;
      if (connection) {
        this.networkInfo = {
          type: connection.type || 'unknown',
          effectiveType: connection.effectiveType || 'unknown',
          downlink: connection.downlink,
          rtt: connection.rtt,
          saveData: connection.saveData
        };

        // 判断是否为慢网络
        this.isSlowNetwork = ['slow-2g', '2g', '3g'].includes(this.networkInfo.effectiveType) ||
                            (this.networkInfo.downlink && this.networkInfo.downlink < 1.5) ||
                            (this.networkInfo.rtt && this.networkInfo.rtt > 300);

        this.updateConfigForNetwork();
      }
    }

    console.log('网络检测结果:', this.networkInfo, '慢网络:', this.isSlowNetwork);
    return this.networkInfo;
  }

  /**
   * 根据网络状况更新配置
   */
  private updateConfigForNetwork(): void {
    if (this.isSlowNetwork) {
      // 慢网络优化配置
      this.config = {
        preloadMode: 'none',
        maxRetries: 5,
        timeoutDuration: 90000,
        bufferThreshold: 10,
        preloadCount: 0,
        enableAdaptiveQuality: true
      };
    } else if (this.networkInfo.effectiveType === '4g') {
      // 4G网络配置
      this.config = {
        preloadMode: 'metadata',
        maxRetries: 3,
        timeoutDuration: 45000,
        bufferThreshold: 20,
        preloadCount: 1,
        enableAdaptiveQuality: true
      };
    } else if (['wifi', '5g'].includes(this.networkInfo.effectiveType)) {
      // 高速网络配置
      this.config = {
        preloadMode: 'auto',
        maxRetries: 2,
        timeoutDuration: 30000,
        bufferThreshold: 30,
        preloadCount: 2,
        enableAdaptiveQuality: false
      };
    }
  }

  /**
   * 测试网络速度
   */
  public async testNetworkSpeed(testUrl: string): Promise<number> {
    try {
      const startTime = Date.now();
      await fetch(testUrl, {
        method: 'HEAD',
        cache: 'no-cache'
      });
      const endTime = Date.now();
      const responseTime = endTime - startTime;

      // 根据响应时间更新网络状态
      if (responseTime > 3000) {
        this.isSlowNetwork = true;
        this.networkInfo.effectiveType = 'slow-2g';
      } else if (responseTime > 1500) {
        this.isSlowNetwork = true;
        this.networkInfo.effectiveType = '3g';
      } else if (responseTime > 800) {
        this.isSlowNetwork = false;
        this.networkInfo.effectiveType = '4g';
      } else {
        this.isSlowNetwork = false;
        this.networkInfo.effectiveType = 'wifi';
      }

      this.updateConfigForNetwork();
      return responseTime;
    } catch (error) {
      console.warn('网络速度测试失败:', error);
      // 默认使用保守策略
      this.isSlowNetwork = true;
      this.updateConfigForNetwork();
      return 5000;
    }
  }

  /**
   * 获取优化后的视频URL
   */
  public getOptimizedVideoUrl(originalUrl: string, retryCount = 0): string {
    let url = originalUrl;

    // 添加优化参数
    const separator = url.includes('?') ? '&' : '?';
    const params = new URLSearchParams();

    // 根据网络状况添加质量参数
    if (this.isSlowNetwork) {
      params.append('quality', 'low');
      params.append('bitrate', '500k');
    } else if (this.networkInfo.effectiveType === '4g') {
      params.append('quality', 'medium');
      params.append('bitrate', '1000k');
    }

    // 添加重试参数避免缓存
    if (retryCount > 0) {
      params.append('retry', retryCount.toString());
      params.append('t', Date.now().toString());
    }

    // 添加网络类型信息
    params.append('network', this.networkInfo.effectiveType);

    const paramString = params.toString();
    if (paramString) {
      url += separator + paramString;
    }

    return url;
  }

  /**
   * 计算缓冲健康度
   */
  public calculateBufferHealth(video: HTMLVideoElement): number {
    if (!video.buffered.length || !video.duration) return 0;

    const buffered = video.buffered;
    const currentTime = video.currentTime;
    const duration = video.duration;

    // 找到当前播放位置的缓冲区间
    let bufferAhead = 0;
    for (let i = 0; i < buffered.length; i++) {
      const start = buffered.start(i);
      const end = buffered.end(i);

      if (currentTime >= start && currentTime <= end) {
        bufferAhead = end - currentTime;
        break;
      }
    }

    // 计算健康度 (30秒缓冲为100%)
    const healthScore = Math.min((bufferAhead / 30) * 100, 100);
    return Math.max(healthScore, 0);
  }

  /**
   * 获取当前配置
   */
  public getConfig(): VideoOptimizationConfig {
    return { ...this.config };
  }

  /**
   * 获取网络信息
   */
  public getNetworkInfo(): NetworkInfo & { isSlowNetwork: boolean } {
    return {
      ...this.networkInfo,
      isSlowNetwork: this.isSlowNetwork
    };
  }

  /**
   * 是否应该预加载
   */
  public shouldPreload(bufferHealth: number, isPlaying: boolean): boolean {
    if (this.isSlowNetwork || this.config.preloadCount === 0) {
      return false;
    }

    if (bufferHealth < this.config.bufferThreshold) {
      return false;
    }

    return !isPlaying || bufferHealth > 50;
  }

  /**
   * 获取重试延迟时间
   */
  public getRetryDelay(retryCount: number): number {
    const baseDelay = this.isSlowNetwork ? 3000 : 1000;
    return baseDelay * Math.pow(1.5, retryCount);
  }

  /**
   * 获取超时时间
   */
  public getTimeoutDuration(retryCount = 0): number {
    const baseTimeout = this.config.timeoutDuration;
    const retryMultiplier = 1 + (retryCount * 0.5);
    return Math.min(baseTimeout * retryMultiplier, 120000); // 最大2分钟
  }

  /**
   * 监听网络变化
   */
  public startNetworkMonitoring(): void {
    if ('connection' in navigator) {
      const connection = (navigator as any).connection;
      if (connection) {
        connection.addEventListener('change', () => {
          console.log('网络状况发生变化');
          this.detectNetwork();
        });
      }
    }
  }
}

// 导出单例实例
export const videoOptimizer = VideoOptimizer.getInstance();
